<!-- -->
<app_modal_dialog_module>
    <div ref="top_div" class="modal fade">
        <div class="modal-dialog modal-content">

            <div class="modal-header">
                <h5 class="modal-title">
                    {opts.title}
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    <i class="glyphicon glyphicon-remove"></i>
                </button>
            </div>

            <div class="modal-body">
                <yield/>
            </div>

            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal" if={opts.buttonOK} onclick={opts.onButtonOK}>
                    {opts.buttonOK}
                </button>
                <button class="btn btn-default" data-dismiss="modal" if={opts.buttonNo} onclick={opts.onButtonNo}>
                    {opts.buttonNo}
                </button>
            </div>
        </div>
    </div>
    <script>
        /* global dispatcher ACTION */
        let rc = dispatcher;
        let self = this;

        // キーボードハンドラ
        // ESC が押されたら消す
        self.onKeyDown = function(e){
            // キーボード
            let key = e.key;
            if (key == "Escape" || key == "Enter") {
                let top = $(self.refs["top_div"]);
                top.modal("hide");
            }
        };

        // エントリポイント
        self.on("mount", () => {
            let top = $(self.refs["top_div"]);
            top.on(
                "hidden.bs.modal",
                () => {
                    // キーボードハンドラを解除
                    window.removeEventListener("keydown", self.onKeyDown);
                }
            );
        });

        self.modal = function (opts, handlers=null) {
            self.opts = opts;
            self.update();
            let top = $(self.refs["top_div"]);

            if (handlers) {
                // shown.bs.modal 等の Bootstrap のハンドラを登録
                for (h in handlers) {
                    top.on(h, handlers[h]);
                }
            }

            // キーボードハンドラを登録
            window.addEventListener("keydown", self.onKeyDown);
            top.modal();
        };
    </script>
</app_modal_dialog_module>


<!-- Notification dialog -->
<app_modal_dialog_launcher>
    <app_modal_dialog_module ref="dialog">
        {opts.body}
    </app_modal_dialog_module>

    <script>
        /* global dispatcher ACTION */
        let rc = dispatcher;

        let self = this;
        self.modal = function (title, body, buttonOK) {
            self.refs.dialog.modal({
                "title": title,
                "body": body,
                "buttonOK": buttonOK
            });
        };

        rc.on(CHANGE.DIALOG_MODAL_ERROR, function (msg) {
            self.modal("Error", msg, "OK");
        });

        rc.on(CHANGE.DIALOG_MODAL_MESSAGE, function (msg) {
            self.modal("Notice", msg, "OK");
        });
    </script>
</app_modal_dialog_launcher>


<!-- リロードの確認 -->
<app_reload_dialog>
    <app_modal_dialog_module ref="dialog">
        {opts.body}
    </app_modal_dialog_module>
    <script>
        /* global dispatcher ACTION */
        let rc = dispatcher;
        let self = this;
        rc.on(CHANGE.DIALOG_CHECK_RELOAD, function (fileName) {
            self.refs.dialog.modal({
                "title": "Notice",
                "body": `"${fileName}" has been updated. Do you want to reload it?`,
                "buttonOK": "Reload",
                "onButtonOK": function () {
                    rc.trigger(ACTION.FILE_RELOAD); // リロードを実行
                },
                "buttonNo": "No",
            });
        });
    </script>
</app_reload_dialog>

<!-- ファイルオープン -->
<app_file_open_dialog>
    <script>
        /* global dispatcher ACTION CHANGE*/
        let rc = dispatcher;
        let remote = require("electron").remote;

        // 読み込みダイアログ
        rc.on(CHANGE.DIALOG_FILE_OPEN, function () {
            const dialog = remote.dialog;
            dialog.showOpenDialog(
                remote.getCurrentWindow(), {
                    properties: ["openFile"],
                    filters: [
                        {
                            name: "Konata log",
                            extensions: ["txt", "text", "log", "out", "gz"]
                        }
                    ],
                    defaultPath: "."
                }
            ).then((result) => {
                if (!result.filePaths || result.canceled) {
                    return;
                }

                // Store にファイルを開いて貰う
                rc.trigger(ACTION.FILE_OPEN, result.filePaths[0]);
            });
        });
    </script>
</app_file_open_dialog>

<!-- stats の表示 -->
<app_stats_dialog>
    
    <app_modal_dialog_module ref="dialog">
        <!-- "form-group" "form-control" は bootstrap のもの -->
        <div class="form-group">
            <input 
                ref="filter" 
                class="form-control" 
                type="text"
                placeholder="Filter pattern for 'Name' column" 
            >
        </div>
        <table class="table table-striped table-sm table-hover">
            <tr>
                <th>Name</th>
                <th>Value</th>
            </tr>
            <tr each="{value, key in opts.stats}">
                <td>{key}</td>
                <td>{value}</td>
            </tr>
        </table>
    </app_modal_dialog_module>

    <script>
        /* global dispatcher ACTION */
        let rc = dispatcher;
        let self = this;
        self.stats = {};

        rc.on(CHANGE.DIALOG_SHOW_STATS, function(stats){
            self.stats = stats;
            let dialog = self.refs.dialog;
            self.refs.dialog.modal(
                {
                    "title": "Stats",
                    "buttonOK": "OK",
                    "stats": self.getFilteredStats()
                },
                { // Bootstrap のダイアログのハンドラ
                    "shown.bs.modal": () => {
                        let filter = dialog.refs.filter;
                        filter.focus();
                    },
                    "hidden.bs.modal": () => { // closeHandler
                        rc.trigger(ACTION.FILE_CLOSE_STATS);
                    }
                }
            );

            // input 内で何か入力があった時のイベントハンドラ
            // 入れ子の内側のものは，refs の参照も入れ子になる
            let filter = self.refs.dialog.refs.filter;
            filter.oninput = function(){
                // 内部でもっている dialog 内の opts を強制的に書き換えて更新
                self.refs.dialog.opts.stats = self.getFilteredStats();
                self.update();
            };

            filter.focus();
        });

        // stats の更新があったときに呼ばれるハンドラ
        rc.on(CHANGE.DIALOG_UPDATE_STATS, function(stats){
            self.stats = stats;
            self.refs.dialog.opts.stats = self.getFilteredStats();
            self.update();
        });

        // stats の中身をフィルタして返す
        self.getFilteredStats = function(){
            let filter = new RegExp(self.refs.dialog.refs.filter.value, "i");
            let stats = {};
            for (let key in self.stats) {
                if (key.match(filter)) {
                    stats[key] = self.stats[key];
                }
            }
            return stats;
        };
    </script>
</app_stats_dialog>

<!-- Settings -->
<app_settings_dialog>
    
    <app_modal_dialog_module ref="dialog">
        <!-- "form-group" "form-control" は bootstrap のもの -->
        <div class="form-group">
            <input 
                ref="filter" 
                class="form-control" 
                type="text"
                placeholder="Search configuration" 
            >
        </div>

        <table class="table table-striped table-sm table-hover">
            <tr each="{data, key in opts.settings}">
                <td>
                    <strong>{key}</strong><br>
                    <small>{data.comment}</small>
                </td>
                <td>
                    <br>
                    <input
                        class="form-control" 
                        ref="{key}"
                        value="{data.value}"
                    >
                </td>
            </tr>
        </table>
    </app_modal_dialog_module>

    <script>
        /* global dispatcher ACTION */
        let rc = dispatcher;
        let self = this;

        rc.on(CHANGE.DIALOG_SHOW_SETTINGS, function(){
            let dialog = self.refs.dialog;
            self.refs.dialog.modal(
                {
                    "title": "Settings",
                    "buttonOK": "OK",
                    "settings": self.getFilteredSettings()
                },
                { // Bootstrap のダイアログのハンドラ
                    "shown.bs.modal": () => {
                        let filter = dialog.refs.filter;
                        filter.focus();
                    },
                    "hidden.bs.modal": () => { // closeHandler
                        rc.trigger(ACTION.FILE_CLOSE_SETTINGS);
                    }
                }
            );

            // input 内で何か入力があった時のイベントハンドラ
            // 入れ子の内側のものは，refs の参照も入れ子になる
            let filter = self.refs.dialog.refs.filter;
            filter.oninput = function(){
                // 内部でもっている dialog 内の opts を強制的に書き換えて更新
                self.refs.dialog.opts.settings = self.getFilteredSettings();
                self.update();
                self.setInputHandler();
            };
            self.setInputHandler();
            filter.focus();
        });

        self.setInputHandler = function(){
            let onFormInput = function(){
                let config = store.config.configItems;
                for (let key in config) {
                    if (key in self.refs.dialog.refs) {
                        let value = self.refs.dialog.refs[key].value;
                        if (store.config[key] != value && value.match(/\d+(\.?\d+)*/)) {
                            rc.trigger(ACTION.KONATA_CHANGE_SETTINGS, key, Number(value));
                        }
                    }
                }
                self.refs.dialog.opts.settings = self.getFilteredSettings();
                self.update();
            };
            let config = store.config.configItems;
            for (let key in config) {
                if (key in self.refs.dialog.refs) {
                    self.refs.dialog.refs[key].oninput = onFormInput;
                }
            }
        }

        // config の中身をフィルタして返す
        self.getFilteredSettings = function(){
            let filter = new RegExp(self.refs.dialog.refs.filter.value, "i");
            let settings = {};
            let config = store.config.configItems;
            for (let key in config) {
                if (key.match(filter) || config[key].comment.match(filter)) {
                    settings[key] = {
                        comment: config[key].comment,
                        value: store.config[key]
                    }
                }
            }
            return settings;
        };
    </script>
</app_settings_dialog>

<app_dialogs>
    <app_modal_dialog_launcher></app_modal_dialog_launcher>
    <app_file_open_dialog></app_file_open_dialog>
    <app_reload_dialog></app_reload_dialog>
    <app_stats_dialog></app_stats_dialog>
    <app_settings_dialog></app_settings_dialog>
</app_dialogs>